package com.ebt.dl.resource;

import java.util.List;

import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.ebt.dl.domain.User;
import com.ebt.dl.service.UserService;
import com.ebt.dl.util.Secured;

@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Transactional
@Component
public class UserResource {

	@Autowired
	private UserService userService;

	@GET
	@Secured
	public List<User> getAll(@Context SecurityContext securityContext) {
		System.out.println("User id: " + securityContext.getUserPrincipal().getName());
		List<User> users = userService.getAllUsers();
		return users;
	}

	@GET
	@Path("{id}")
	@Secured
	public User getOne(@PathParam("id") long id) {
		User user = userService.getUserById(id);
		if (user == null) {
			throw new WebApplicationException(Response.Status.NOT_FOUND);
		}
		return user;

	}

	@POST
	@Secured
	public Response save(@Valid User user) {
		if (user.getId() != null) {
			throw new WebApplicationException(Response.Status.BAD_REQUEST);
		}
		if (userService.getUserByUserId(user.getUserId()) != null) {
			throw new WebApplicationException(Response.Status.CONFLICT);
		}
		return Response.status(Response.Status.CREATED).entity(userService.saveUser(user)).build();
	}

	@PUT
	@Path("{id}")
	@Secured
	public Response update(@PathParam("id") long id, @Valid User user) {
		if (userService.getUserById(id) == null) {
			throw new WebApplicationException(Response.Status.NOT_FOUND);
		}
		user.setId(id);
		userService.saveUser(user);
		return Response.status(Response.Status.NO_CONTENT).build();

	}

	@DELETE
	@Path("{id}")
	@Secured
	public Response deleteUser(@PathParam("id") long id) {
		User user = userService.getUserById(id);
		if (user == null) {
			throw new WebApplicationException(Response.Status.NOT_FOUND);
		}
		userService.deleteUser(id);
		return Response.status(Response.Status.NO_CONTENT).build();
	}
}
